//
//  ByUIOrderCommitVC.m
//  itboye_shop_ios
//
//  Created by pro on 17/2/9.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIOrderCommitVC.h"

// vc
#import "ByUIOrderPayVC.h"                              // 支付界面
#import "ByUIAddressVC.h"                               // 地址选择

// view
#import "ByViewOrderCommitToolBar.h"                    // 工具栏

// cell
#import "ByCellCommitOrderAddressHad.h"                 // 地址（已选择）
#import "ByCellCommitOrderProduct.h"                    // 商品
#import "ByCellCommitOrderOrderInfo.h"                  // 订单信息

// api
#import "ByApiAddress.h"                                // 地址api
#import "ByApiCommitOrder.h"                            // 订单递交api

@interface ByUIOrderCommitVC () <UITableViewDelegate, UITableViewDataSource>

// view
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) ByViewOrderCommitToolBar *toolBar;    // 工具栏

// data
@property (nonatomic, strong) ByModelAddress *addressModel;         // 地址model
@property (nonatomic, strong) NSMutableArray *notesArray;           // 留言数组

@end

@interface ByUIOrderCommitVC ()

@end

@implementation ByUIOrderCommitVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"提交订单";
    
    [self addLeftBackBarButtonItem];
    
    // 创建table
    [self createTableView];
    // 设置工具栏回调
    [self setToolbarBlock];

    
    // 获取默认地址
    [self getDefaultAddress];
}
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [ByCoreToolAlert hideHud];
}

#pragma mark - 懒加载
- (NSMutableArray *)notesArray {
    
    if (!_notesArray) {
        _notesArray = [[NSMutableArray alloc] initWithCapacity:_selectedPorducts.count];
        for (int i = 0; i < _selectedPorducts.count; i ++) {
            [_notesArray addObject:@""];
        }
    }
    return _notesArray;
}
// 工具栏
- (ByViewOrderCommitToolBar *)toolBar {
    
    if (!_toolBar) {
        _toolBar = [[ByViewOrderCommitToolBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        _toolBar.totalPrice = self.totalPrice;
        _toolBar.bottom = SCREEN_HEIGHT - 64;
        [self.view addSubview:_toolBar];
    }
    return _toolBar;
}

#pragma mark - 回调处理
- (void)setToolbarBlock {
    
    __weak typeof(self) weakself = self;
    self.toolBar.commitBlock = ^ {
        
        [weakself createOrder];
    };
}

#pragma mark - 网络请求
// 获取默认地址
- (void)getDefaultAddress {
    
    [self performSelector:@selector(loading:) withObject:@"获取默认地址.." afterDelay:0.01];
    
    ByModelAddress *params = [[ByModelAddress alloc] init];
    params.uid = BY_USER.uid;
    params.s_id = BY_USER.s_id;
    [ByApiAddress defaultAddressGet:params success:^(ByNetBaseResult *result) {
        
        [ByCoreToolAlert hideHud];
        
        self.addressModel = result.data;
        [self.table reloadData];
        
    } failure:^(ByNetBaseResult *result) {
        
        if ([result.msg isEqualToString:@"空数据"]) {
            [ByCoreToolAlert showFailureWithText:@"无默认地址"];
        } else {
            [ByCoreToolAlert showFailureWithText:result.msg];
        }
    }];
}
// 调用创建订单接口
- (void)createOrder {
    
    if (!self.addressModel) {
        [ByCoreToolAlert showFailureWithText:@"请先选择地址"];
        return;
    }
    
    ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
    params.s_id = BY_USER.s_id;
    params.uid = BY_USER.uid;
    params.address_id = _addressModel.address_id;
    // 拼接id数组
    NSMutableArray *ids = [[NSMutableArray alloc] init];
    [self.selectedPorducts enumerateObjectsUsingBlock:^(ByModelShopCar *storeModel, NSUInteger index1, BOOL * _Nonnull stop) {
        
        [storeModel.item_list enumerateObjectsUsingBlock:^(ByModelShopCarListItem *itemModel, NSUInteger index2, BOOL * _Nonnull stop) {
            
            [ids addObject:itemModel.id];
        }];
    }];
    params.ids = [ids componentsJoinedByString:@","];
    // 拼接留言数组
    for (int i = 0; i < self.notesArray.count; i ++) {
        ByModelShopCar *storeModel = self.selectedPorducts[i];
        [self.notesArray replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%@:%@|", storeModel.store_id, self.notesArray[i]]];
    }
    params.note = [self.notesArray componentsJoinedByString:@""];
    
    [self performSelector:@selector(loading:) withObject:@"正在提交订单.." afterDelay:0.01];
    [ByApiCommitOrder createOrder:params success:^(ByNetBaseResult *result) {
        
        [ByCoreToolAlert hideHud];
        
        ByUIOrderPayVC *vc = [[ByUIOrderPayVC alloc] init];
        vc.type = 0;
        vc.fee = [NSString stringWithFormat:@"%.2lf", self.totalPrice];
        vc.payModel = result.data;
        [self by_normalPush:vc hasNavi:YES];
        
    } failure:^(ByNetBaseResult *result) {
        
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}

- (void)loading:(NSString *)text {
    
    [ByCoreToolAlert showLoadind:text];
}

#pragma mark - create view
// 创建表视图
- (void)createTableView {
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - self.toolBar.height) style:UITableViewStyleGrouped];
    self.table.backgroundColor = TABLE_COLOR;
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    
    self.table.tableFooterView = [UIView new];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // +1是地址栏
    return self.selectedPorducts.count + 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        ByModelShopCar *storeModel = self.selectedPorducts[section - 1];
        return storeModel.item_list.count + 1;
    }
    
    return 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        // 已选择收货地址
        if (self.addressModel) {
            ByCellCommitOrderAddressHad *cell = [tableView dequeueReusableCellWithIdentifier:@"addressDidSelectedCell"];
            if (cell == nil) {
                cell = [[ByCellCommitOrderAddressHad alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"addressDidSelectedCell"];
            }
            
            cell.model = _addressModel;
            
            return cell;
        }
        // 未选择收货地址
        else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addressDidNotSelectedCell"];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"addressDidNotSelectedCell"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                cell.textLabel.text = @"请选择地址";
                cell.textLabel.font = FONT(15);
            }
            
            return cell;
        }
        
    }
    
    // 店铺商品信息
    else {
        
        // 店铺model
        ByModelShopCar *storeModel = self.selectedPorducts[indexPath.section - 1];

        // 商品
        if (indexPath.row < storeModel.item_list.count) {
            ByCellCommitOrderProduct *cell = [tableView dequeueReusableCellWithIdentifier:@"productCell"];
            if (cell == nil) {
                cell = [[ByCellCommitOrderProduct alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"productCell"];
            }
            
            // 设置属性
            cell.model = storeModel.item_list[indexPath.row];
            
            return cell;
        }
        // 配送方式，留言，总计等
        else {
           
            ByCellCommitOrderOrderInfo *cell = [tableView dequeueReusableCellWithIdentifier:@"infoCell"];
            if (cell == nil) {
                cell = [[ByCellCommitOrderOrderInfo alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"infoCell"];
            }
            
            cell.storeModel = storeModel;
            
            // 留言
            cell.notesFetchBlock = ^ (NSString *notes) {
                
                [self.notesArray replaceObjectAtIndex:indexPath.section - 1 withObject:notes];
            };
            
            return cell;
        
        }
        
        
    }
    
    return [UITableViewCell new];
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        if (_addressModel) {
            return 100;
        } else {
            return 44;
        }
    }
    
    else {
        ByModelShopCar *storeModel = self.selectedPorducts[indexPath.section - 1];
        if (indexPath.row < storeModel.item_list.count) {
            return 100;
        } else {
            return 44 * 3;
        }
    }
    
    
    
    return 44;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    // 不是地址栏，则是店铺的商品，需要有头视图
    if (section != 0) {
        return 44;
    }
    
    return 0.01;
}
// 组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section != 0) {
        
        ByModelShopCar *storeModel = self.selectedPorducts[section - 1];
        
        UIView *header = [[UIView alloc] init];
        header.backgroundColor = [UIColor whiteColor];
        // 图片
        UIImageView *logoView = [[UIImageView alloc] initWithFrame:CGRectMake(BY_TABLE_LEFT_MARGIN, 11, 20, 20)];
        [header addSubview:logoView];
        [logoView setImageWithURL:[NSURL URLWithString:storeModel.store_logo] placeholderImage:DEFAULT_IMAGE];
        
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(BY_TABLE_LEFT_MARGIN * 2 + 20, 0, 200, 44)];
        nameLabel.font = FONT(14);
        nameLabel.text = storeModel.store_name;
        nameLabel.textColor = [UIColor blackColor];
        nameLabel.textAlignment = NSTextAlignmentLeft;
        [header addSubview:nameLabel];
        
        return header;
    }
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 5;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [UIView new];
}


// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 选择地址，并回调
    if (indexPath.section == 0) {
        ByUIAddressVC *vc = [[ByUIAddressVC alloc] init];
        [self by_normalPush:vc hasNavi:YES];
        [vc setDidSelectAddressBlock:^(ByModelAddress *model) {
            self.addressModel = model;
            [self.table reloadData];
        }];
    }
}

#pragma mark - 点击事件


@end
